package tomoto.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Helper utility to operate IO streams
 * 
 * @author Tomoto Shimizu Washio
 * 
 */
public class StreamUtil {
	/**
	 * Platform's default line separator.
	 */
	public static final String LINE_SEPARATOR = System.getProperty("line.separator");

	/**
	 * Copy all data from readable to appendable.
	 * 
	 * @param w appendable to copy to
	 * @param r readable to copy from
	 * @throws IOException IO error
	 */
	public static void copy(Appendable w, Readable r) throws IOException {
		CharBuffer buf = CharBuffer.allocate(1024);
		while (true) {
			int readSize = r.read(buf);
			if (readSize < 0) break;
			buf.rewind();
			w.append(buf, 0, readSize);
		}
	}

	/**
	 * Read all lines from a reader into a list of String.
	 * 
	 * @param r reader to read from
	 * @return a list of string that contains all lines from the reader
	 * @throws IOException IO error
	 */
	public static List<String> readAllPerLine(Reader r) throws IOException {
		List<String> result = new ArrayList<String>();
		String line;
		BufferedReader br = new BufferedReader(r);
		while ((line = br.readLine()) != null) {
			result.add(line);
		}
		return result;
	}
	
	public static String readAll(Reader r) throws IOException {
		StringBuffer sb = new StringBuffer();
		copy(sb, r);
		return sb.toString();
	}

}
